@miso.ai/doggoganger 0.9.1-beta.14 → 0.9.1-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/umd/doggoganger-browser.min.js +1 -1
- package/package.json +1 -1
- package/src/data/answers.js +12 -2
- package/src/data/fields.js +4 -2
- package/src/data/lorem.js +5 -14
- package/src/data/markdown/index.js +70 -28
- package/src/data/utils.js +14 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=e()}(this,(function(){"use strict";function t(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(t^16*Math.random()>>t/4).toString(16)))}function e(t,e){return null!=e&&e>t?t+Math.floor(Math.random()*(e-t)):t}function n(t,n){const r=e(...n),o=[];for(let e=0;r>e;e++)o.push(t());return o}function r(){return Math.random().toString(36).substring(2,10)}function o(t){for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function s(t){return`https://picsum.photos/seed/${Math.floor(1e3*Math.random())}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}function i(t){const e=new Date(t).toISOString();return e.endsWith("Z")?e.slice(0,-1):e}function a(t,e){return void 0!==e?Math.ceil(t*e):t}function u(){return c()+c()+c()}function c(){return 2*Math.random()-1}var l=Object.freeze({__proto__:null,formatDatetime:i,gaussRandom:u,id:r,imageUrl:s,randomInt:e,repeat:n,sample:a,shuffle:o,uuid:t}),f=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","curabitur","vel","hendrerit","libero","eleifend","blandit","nunc","ornare","odio","ut","orci","gravida","imperdiet","nullam","purus","lacinia","a","pretium","quis","congue","praesent","sagittis","laoreet","auctor","mauris","non","velit","eros","dictum","proin","accumsan","sapien","nec","massa","volutpat","venenatis","sed","eu","molestie","lacus","quisque","porttitor","ligula","dui","mollis","tempus","at","magna","vestibulum","turpis","ac","diam","tincidunt","id","condimentum","enim","sodales","in","hac","habitasse","platea","dictumst","aenean","neque","fusce","augue","leo","eget","semper","mattis","tortor","scelerisque","nulla","interdum","tellus","malesuada","rhoncus","porta","sem","aliquet","et","nam","suspendisse","potenti","vivamus","luctus","fringilla","erat","donec","justo","vehicula","ultricies","varius","ante","primis","faucibus","ultrices","posuere","cubilia","curae","etiam","cursus","aliquam","quam","dapibus","nisl","feugiat","egestas","class","aptent","taciti","sociosqu","ad","litora","torquent","per","conubia","nostra","inceptos","himenaeos","phasellus","nibh","pulvinar","vitae","urna","iaculis","lobortis","nisi","viverra","arcu","morbi","pellentesque","metus","commodo","ut","facilisis","felis","tristique","ullamcorper","placerat","aenean","convallis","sollicitudin","integer","rutrum","duis","est","etiam","bibendum","donec","pharetra","vulputate","maecenas","mi","fermentum","consequat","suscipit","aliquam","habitant","senectus","netus","fames","quisque","euismod","curabitur","lectus","elementum","tempor","risus","cras"];function d({decorates:t=[],output:e="string",size:n,min:r,max:o,...s}={}){let i=b(n||[r,o])(h(s));for(const e of t)i=p(e)(i);return p(e)(i)}const m={string:g,array:_,title:y,description:v,multiline:w};function p(t){switch(typeof t){case"string":return m[t]();case"function":return t;case"object":if(Array.isArray(t)){const[e,n={}]=t;return m[e](n)}}throw Error("Unrecognized decorator/output form: "+t)}function*h({words:t=f,fixedStarts:e=0}={}){const n=t.length;for(let r=0;;r++)yield t[e>r?r:Math.floor(Math.random()*n)]}function g({separator:t=" "}={}){return e=>[...e].join(t)}function _(){return t=>[...t]}function w({wordsPerLine:t={avg:10,std:3,min:1}}={}){return e=>{let n=q(t),r="";for(let o of e)r&&(0==n--?(r+="\n",n=q(t)):r+=" "),r+=o;return r}}function b(t=[5,10]){const n="number"==typeof t?t:e(...t);return function*(t){let e=0;for(let r of t){if(e++>=n)break;yield r}}}function y({}={}){return function*(t){for(let e of t)yield z(e)}}function v({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:e="."}={}){return function*(n){let r,o=0;for(let s of n)r&&(yield r),r=s,0===o&&(r=z(r),o=q(t)),0==--o&&(r+=e);r&&(r.endsWith(e)||(r+=e),yield r)}}function z(t){return t[0].toUpperCase()+t.substring(1)}function q(t){if("number"==typeof t)return Math.round(e);let{avg:e,std:n,min:r,max:o}=t;void 0===n&&(n=e/4);let s=u()*n+e;return void 0!==r&&(s=Math.max(r,s)),void 0!==o&&(s=Math.min(o,s)),Math.round(s)}var $=Object.freeze({__proto__:null,array:_,base:h,description:v,limit:b,lorem:d,multiline:w,string:g,title:y});const M="// module\nimport { a, b } from './module';\nimport * as module from './module';\nimport module from './module';\nexport default module;\nexport const a = 0;\nexport * from './module';\nexport * as module from './module';\n\n// variables\nlet a = 10;\nconst b = 20;\n\n// function declaration\nfunction sum(x, y) {\n return x + y;\n}\n\n// generator function\nfunction* iterator() {\n yield 0;\n yield 1;\n}\n\n// arrow function\nconst multiply = (x, y) => x * y;\n\n// class\nclass Person {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n greet() {\n console.log('Hello, my name is Miso.');\n }\n}\n\n// primitive\nconst str = 'Hello, world!';\nconst num = 10.99;\n\n// object\nconst person = new Person('John', 30);\nperson.greet();\n\n// object literal\nconst object = {\n name: 'John',\n [x]: 10,\n ...props,\n};\n\n// array literal\nconst arr = [1, 2, 3, 4, 5, ...props];\n\n// regexp literal\nconst regexp = /\\w+/g;\n\n// operators\nconst sum = a + b;\nconst product = a * b;\nconst negation = -a;\nconst max = a > b ? a : b;\n\n// flow control\nlet i = 9;\nfor (const n of arr) {\n if (n > i) {\n console.log(n);\n }\n i++;\n}\n\n// async/await\n(async () => {\n const result = await asyncFunction();\n})();\n\n// try/catch\ntry {\n} catch (e) {\n}\n\n// destructuring\nconst { name, age, ...rest } = person;\nconst [ x, y, ...rest ] = arr;\n\n// template literals\nconsole.log(`The sum of ${a} and ${b} is ${sum(a, b)}.`);";var x=Object.freeze({__proto__:null,javascript:function(){return M},js:function(){return M}});function j({features:t,blocks:e=[8,12],sampling:n=1}={}){let r=[];return[r,t]=function(t=[]){const e=new Set,n=[];for(const r of t)if(r.startsWith("lang-")){let t=r.slice(5);"javascript"===t&&(t="js"),e.add(t)}else n.push(r);return[[...e],n]}(t),function(t,e){const n=[];for(const r of t)1>e&&Math.random()>=e||n.push(r());return n}([()=>S({features:t}),()=>A({features:t}),...r.map((e=>()=>O({lang:e,features:t}))),...r.length?[]:[()=>O({features:t})],()=>A({features:t}),()=>D({features:t}),()=>C(),()=>A({features:t}),()=>k(),()=>S({features:t}),()=>A({features:t}),()=>F({features:t}),()=>A({features:t})],n).join("\n\n")}function k(){return"*-_".charAt(e(0,2)).repeat(e(3,6))}function S({level:t=[1,6],size:n=[1,8],content:r}){const o=r||d({size:n});return`${"#".repeat(e(...t))} ${o}`}function O({lang:t,content:n,size:r,fenceChar:o="`"}){return"random"===o&&(o="`~".charAt(e(0,1))),n=n||B({lang:t,size:r}),`${o.repeat(3)}${t||""}\n${n}\n${o.repeat(3)}`}function A({size:t=[20,50]}){return d({size:t,decorates:["description",U()]})}function D({columns:t=[2,4],rows:n=[2,8]}){t=e(...t),n=e(...n);const r=[...K({size:1},t-1),{size:[3,8]}],o=[d({size:t,output:"array"}),r.map((()=>"---"))];for(let t=0;n-1>t;t++)o.push(r.map((({size:t})=>d({size:t}))));return o.map(J).join("\n")}function C({url:t,imageSize:e=[400,250],...n}={}){return t=t||s(e),``}const T=["ordered","bullet","task"];function F({features:t,type:n="random",count:r=[1,8],size:o=[5,15]}){r="number"==typeof r?r:e(...r);const s="random"===n?T[Math.floor(3*Math.random())]:n,i=[];for(;r>0;){const a=e(1,r);let u=A({features:t,size:o});a>1&&(u+="\n"+F({features:t,type:n,count:a-1,size:o})),i.push(W(s,u)),r-=a}return i.join("\n")}const I={"code-span":()=>["`","`"],"emphasis-1":()=>K(H(1),2),"emphasis-2":()=>K(H(2),2),"emphasis-3":()=>K(H(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]};function H(t=[1,3]){return t="number"==typeof t?t:e(...t),"_*".charAt(e(0,1)).repeat(t)}const L=Object.keys(I),P=new Set(L);function U({features:t=L,size:n=[1,3],rest:r=[0,8]}={}){t=t.filter((t=>P.has(t)));const s=o([...t]);let i=s.length-1;const a=()=>"number"==typeof r?r:e(...r);return function*(r){let o,u,c=a();for(const l of r)if(u&&(yield u),0===c)if(o)u=`${l}${o}`,o=void 0,c=a();else{const[r,a]=I[0>i?t[e(0,t.length-1)]:s[i--]]();u=`${r}${l}`,o=a,c="number"==typeof n?n:e(...n)}else u=l,c--;u&&(yield void 0!==o?`${u}${o}`:u)}}function E({size:t=[1,3],content:e}={}){return e||d({size:t})}function R(t,e){return e.split("\n").map((e=>" ".repeat(t)+e)).join("\n")}function W(t,e){const[n,r]=e.split("\n",2),o=`${function(t,e="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===e?.5>Math.random():e)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}(t)} ${n}`;return r?o+"\n"+R("ordered"===t?3:2,r):o}function B({lang:t,size:e=[10,30]}){return t&&x[t]?x[t]():d({output:"multiline",size:e})}function J(t){return`| ${t.join(" | ")} |`}function K(t,e){const n=[];for(let r=0;e>r;r++)n.push("function"==typeof t?t():t);return n}var G=Object.freeze({__proto__:null,atxHeading:S,blockquote:function({size:t=[3,5]}){return d({size:t}).split("\n").map((t=>"> "+t)).join("\n")},codeSpan:function(t){return`\`${E(t)}\``},decorate:U,emphasis:function({level:t=[1,3],options:n}){t="number"==typeof t?t:e(...t);const r="_*".charAt(e(0,1)).repeat(t);return`${r}${E(n)}${r}`},fencedCodeBlock:O,hr:k,image:C,indent:R,indentedCodeBlock:function({lang:t,content:e,size:n}){return R(4,e=e||B({lang:t,size:n}))},link:function({url:t="https://miso.ai",...e}={}){return`[${E(e)}](${t})`},linkReferenceDefinition:function({label:t,destination:e,title:n}){return`[${t}]: ${e}${void 0!==n?" "+n:""}`},list:F,listItem:W,markdown:j,paragraph:A,setextHeading:function({level:t=[1,2],size:n=[1,8],content:r}){return`${r||d({size:n})}\n${"=-".charAt(e(...t)-1).repeat(3)}`},table:D});const N=864e5,Q=7*N;function V({}={}){const t=Date.now()-N,e=t-8*Q;return new Date(e+Math.random()*(t-e)).toISOString()}function Z({size:t=300}={}){return s(t)}function X({size:t=[1,3]}={}){return d({size:t,decorates:["title"],output:"array"})}function Y({size:t=[1,4]}={}){return d({size:t,output:"array"})}function tt({size:t=[2,6]}={}){return d({size:t,decorates:["title"]})}function et({size:t=[10,20],...e}={}){return d({size:t,decorates:[Object.keys(e).length?["description",e]:"description"]})}function nt({paragraphs:t=8,sections:e,paragraph:n,image:r}={}){n={size:[30,60],...n},r={size:[480,270],...r},void 0===e&&(e=Math.floor(t*(1+Math.random())/4));const o=[],s=t/(e=Math.max(1,Math.min(e,t)));let i=0;for(let t=0;e>t;t++){for(t>0&&o.push(`<h4>${tt()}</h4>`);i++<(t+1)*s;)o.push(`<p>${et(n)}</p>`);o.push(`<div class="image-container"><img src="${Z(r)}"></div>`)}return o.join("")}function rt(){return Math.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}function ot(){return Math.floor(1e4*Math.random())/100}function st(){return Math.floor(500*Math.random())/100+1}function it({format:t,sampling:e,features:n}){return"markdown"===t?j({sampling:e,features:n}):d({min:a(50,e),max:a(50,e),decorates:["description"]})}var at=Object.freeze({__proto__:null,answer:it,authors:X,availability:rt,date:V,description:et,html:nt,image:Z,price:ot,rating:st,tags:Y,title:tt});function*ut({rows:t,...e}={}){for(let n=0;t>n;n++)yield ct({...e,index:n})}function ct({}={}){const t=r(),e=n(ot,[1,2]);return e.sort(),{product_id:t,authors:X(),categories:[],tags:Y(),title:tt(),description:et(),cover_image:Z(),url:"https://dummy.miso.ai/products/"+t,sale_price:e[0],original_price:e[e.length-1],rating:st(),availability:rt()}}const lt=new Set(["cover_image","url","created_at","updated_at","published_at"]);function*ft({rows:t,...e}={}){for(let n=0;t>n;n++)yield dt({...e,index:n})}function dt({html:t,fl:e=[]}={}){const n={product_id:r(),authors:X(),categories:[],tags:Y(),title:tt({size:[4,10]}),snippet:et({size:[20,40]}),html:nt(t)};for(const t of e)lt.has(t)&&(n[t]=mt(n,t));return n}function mt({product_id:t},e){switch(e){case"cover_image":return Z();case"url":return"/products/"+t;case"created_at":case"updated_at":case"published_at":return V()}}function*pt({rows:t=5,...e}={}){for(let n=0;t>n;n++)yield ht({...e,index:n})}function ht({}={}){return et({size:[4,8],punctuation:"?"})}function gt({question:e,parent_question_id:n,source_fl:r=["cover_image","url"],related_resource_fl:o=["cover_image","url"],timestamp:s=Date.now()},{answerFormat:a="markdown",answerSampling:u,answerLanguages:c=[]}={}){const l=t(),f=i(s),d=void 0!==u?Math.max(0,Math.min(1,u)):void 0,m=it({format:a,sampling:d,features:c.length?c.map((t=>"lang-"+t)):void 0}),p=[...ft({rows:_t(6,8,d),fl:o})].map(wt);return{question:e,question_id:l,...n&&{parent_question_id:n},datetime:f,answer:m,sources:[...ft({rows:_t(4,6,d),fl:r})].map(wt),related_resources:p,followup_questions:[...pt({rows:_t(3,6)})]}}function _t(t,n,r){return e(a(t,r),a(n,r))}function wt({html:t,...e}){return e}var bt=Object.freeze({__proto__:null,answer:gt,articles:ft,fields:at,lorem:$,md:G,products:ut,questions:pt,utils:l});const yt=[{name:"fetch",duration:1.5,text:"Checking the question and fetching results... "},{name:"verify",duration:1.5,text:"Verifying results... "},{name:"generate",duration:1.5,text:"Generating answer... "}];class vt{constructor(t={}){this._options=t,this._answers=new Map}questions(t,e={}){const n=new zt(t,{...this._options,...e}),{question_id:r}=n;return this._answers.set(r,n),{question_id:r}}answer(t){const e=this._answers.get(t);if(!e){const e=Error("Question not found: "+t);throw e.status=404,e}return e.get()}related_questions(t){return{related_questions:[...pt(t)]}}}class zt{constructor(t,{answerFormat:e,answerSampling:n,answerLanguages:r,...o}={}){this._options=Object.freeze(o);const s=this.timestamp=Date.now();this._data=gt({...t,timestamp:s},{answerFormat:e,answerSampling:n,answerLanguages:r})}get question_id(){return this._data.question_id}get(){const t=(Date.now()-this.timestamp)*(this._options.speedRate||1)/1e3,[e,n,r]=this._answer(t),o=this._sources(t,r),s=this._related_resources(t,r),i=this._followup_questions(t,r),{question_id:a,question:u,datetime:c,parent_question_id:l}=this._data;return{answer:n,answer_stage:e,datetime:c,finished:r,parent_question_id:l,question:u,question_id:a,sources:o,related_resources:s,followup_questions:i}}_answer(t){for(const e of yt)if(0>(t-=e.duration))return[e.name,e.text,!1];const{answer:e}=this._data,n=Math.floor(100*t),r=n>=e.length;return["result",r?e:e.slice(0,n),r]}_sources(t,e){const{sources:n}=this._data;if(e)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}_related_resources(t,e){const{related_resources:n}=this._data;if(e)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}_followup_questions(t,e){const{followup_questions:n}=this._data;if(e||!n)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}}class qt{constructor(t){this._options=t}search({rows:t=5}){return{products:[...ut({rows:t})]}}}class $t{constructor(t){this._options=t}user_to_products({rows:t=5}){return{products:[...ut({rows:t})]}}product_to_products({rows:t=5}){return{products:[...ut({rows:t})]}}}class Mt{constructor(t){this._options=t}upload(t){return[]}}class xt{constructor(t){this._options=t}upload(t){return[]}ids(){const t=[];for(let e=0;5e3>e;e++)t.push(jt(e));return{ids:t}}}function jt(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class kt{constructor(t){this.ask=new vt(t),this.search=new qt(t),this.recommendation=new $t(t),this.interactions=new Mt(t),this.products=new xt(t)}}return{buildApi:(...t)=>new kt(...t),data:bt}}));
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).doggoganger=e()}(this,(function(){"use strict";function t(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(t^16*Math.random()>>t/4).toString(16)))}function e(t,e){return null!=e&&e>t?t+Math.floor(Math.random()*(e-t+1)):t}function n(t,n){const r=e(...n),o=[];for(let e=0;r>e;e++)o.push(t());return o}function r(){return Math.random().toString(36).substring(2,10)}function o(t){for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function s(t){return`https://picsum.photos/seed/${Math.floor(1e3*Math.random())}/${Array.isArray(t)?t.length>1?`${t[0]}/${t[1]}`:""+t[0]:""+t}`}function i(t){const e=new Date(t).toISOString();return e.endsWith("Z")?e.slice(0,-1):e}function a(t,e){return void 0!==e?Math.ceil(t*e):t}function u(){return c()+c()+c()}function c(){return 2*Math.random()-1}function*l(t,e){let n;for(const r of t)n&&(yield*e(n)),n=r;n&&(yield*e(n,!0))}var d=Object.freeze({__proto__:null,formatDatetime:i,gaussRandom:u,id:r,imageUrl:s,iterateWithLastItemSignal:l,randomInt:e,repeat:n,sample:a,shuffle:o,uuid:t}),f=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","curabitur","vel","hendrerit","libero","eleifend","blandit","nunc","ornare","odio","ut","orci","gravida","imperdiet","nullam","purus","lacinia","a","pretium","quis","congue","praesent","sagittis","laoreet","auctor","mauris","non","velit","eros","dictum","proin","accumsan","sapien","nec","massa","volutpat","venenatis","sed","eu","molestie","lacus","quisque","porttitor","ligula","dui","mollis","tempus","at","magna","vestibulum","turpis","ac","diam","tincidunt","id","condimentum","enim","sodales","in","hac","habitasse","platea","dictumst","aenean","neque","fusce","augue","leo","eget","semper","mattis","tortor","scelerisque","nulla","interdum","tellus","malesuada","rhoncus","porta","sem","aliquet","et","nam","suspendisse","potenti","vivamus","luctus","fringilla","erat","donec","justo","vehicula","ultricies","varius","ante","primis","faucibus","ultrices","posuere","cubilia","curae","etiam","cursus","aliquam","quam","dapibus","nisl","feugiat","egestas","class","aptent","taciti","sociosqu","ad","litora","torquent","per","conubia","nostra","inceptos","himenaeos","phasellus","nibh","pulvinar","vitae","urna","iaculis","lobortis","nisi","viverra","arcu","morbi","pellentesque","metus","commodo","ut","facilisis","felis","tristique","ullamcorper","placerat","aenean","convallis","sollicitudin","integer","rutrum","duis","est","etiam","bibendum","donec","pharetra","vulputate","maecenas","mi","fermentum","consequat","suscipit","aliquam","habitant","senectus","netus","fames","quisque","euismod","curabitur","lectus","elementum","tempor","risus","cras"];function p({decorates:t=[],output:e="string",size:n,min:r,max:o,...s}={}){let i=y(n||[r,o])(g(s));for(const e of t)i=h(e)(i);return h(e)(i)}const m={string:_,array:w,title:v,description:$,multiline:b};function h(t){switch(typeof t){case"string":return m[t]();case"function":return t;case"object":if(Array.isArray(t)){const[e,n={}]=t;return m[e](n)}}throw Error("Unrecognized decorator/output form: "+t)}function*g({words:t=f,fixedStarts:e=0}={}){const n=t.length;for(let r=0;;r++)yield t[e>r?r:Math.floor(Math.random()*n)]}function _({separator:t=" "}={}){return e=>[...e].join(t)}function w(){return t=>[...t]}function b({wordsPerLine:t={avg:10,std:3,min:1}}={}){return e=>{let n=q(t),r="";for(let o of e)r&&(0==n--?(r+="\n",n=q(t)):r+=" "),r+=o;return r}}function y(t=[5,10]){const n="number"==typeof t?t:e(...t);return function*(t){let e=0;for(let r of t){if(e++>=n)break;yield r}}}function v({}={}){return function*(t){for(let e of t)yield z(e)}}function $({wordsPerSentence:t={avg:24,std:5,min:1},punctuation:e="."}={}){return function*(n){let r=0;yield*l(n,(function*(n,o){0===r&&(n=z(n),r=q(t)),(0==--r||o)&&(n+=e),yield n}))}}function z(t){return t[0].toUpperCase()+t.substring(1)}function q(t){if("number"==typeof t)return Math.round(e);let{avg:e,std:n,min:r,max:o}=t;void 0===n&&(n=e/4);let s=u()*n+e;return void 0!==r&&(s=Math.max(r,s)),void 0!==o&&(s=Math.min(o,s)),Math.round(s)}var M=Object.freeze({__proto__:null,array:w,base:g,description:$,limit:y,lorem:p,multiline:b,string:_,title:v});const x="// module\nimport { a, b } from './module';\nimport * as module from './module';\nimport module from './module';\nexport default module;\nexport const a = 0;\nexport * from './module';\nexport * as module from './module';\n\n// variables\nlet a = 10;\nconst b = 20;\n\n// function declaration\nfunction sum(x, y) {\n return x + y;\n}\n\n// generator function\nfunction* iterator() {\n yield 0;\n yield 1;\n}\n\n// arrow function\nconst multiply = (x, y) => x * y;\n\n// class\nclass Person {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n greet() {\n console.log('Hello, my name is Miso.');\n }\n}\n\n// primitive\nconst str = 'Hello, world!';\nconst num = 10.99;\n\n// object\nconst person = new Person('John', 30);\nperson.greet();\n\n// object literal\nconst object = {\n name: 'John',\n [x]: 10,\n ...props,\n};\n\n// array literal\nconst arr = [1, 2, 3, 4, 5, ...props];\n\n// regexp literal\nconst regexp = /\\w+/g;\n\n// operators\nconst sum = a + b;\nconst product = a * b;\nconst negation = -a;\nconst max = a > b ? a : b;\n\n// flow control\nlet i = 9;\nfor (const n of arr) {\n if (n > i) {\n console.log(n);\n }\n i++;\n}\n\n// async/await\n(async () => {\n const result = await asyncFunction();\n})();\n\n// try/catch\ntry {\n} catch (e) {\n}\n\n// destructuring\nconst { name, age, ...rest } = person;\nconst [ x, y, ...rest ] = arr;\n\n// template literals\nconsole.log(`The sum of ${a} and ${b} is ${sum(a, b)}.`);";var j=Object.freeze({__proto__:null,javascript:function(){return x},js:function(){return x}});function k({sources:t,citation:e,features:n,blocks:r=[8,12],sampling:o=1}={}){let s=[];[s,n]=function(t=[]){const e=new Set,n=[];for(const r of t)if(r.startsWith("lang-")){let t=r.slice(5);"javascript"===t&&(t="js"),e.add(t)}else n.push(r);return[[...e],n]}(n);let i=function(t,e){const n=[];for(const r of t)1>e&&Math.random()>=e||n.push(r());return n}([()=>O({features:n}),()=>C({sources:t,citation:e,features:n}),...s.map((t=>()=>A({lang:t,features:n}))),...s.length?[]:[()=>A({features:n})],()=>C({sources:t,citation:e,features:n}),()=>D({features:n}),()=>I(),()=>C({sources:t,citation:e,features:n}),()=>S(),()=>O({features:n}),()=>C({sources:t,citation:e,features:n}),()=>T({features:n}),()=>C({sources:t,citation:e,features:n})],o).join("\n\n");if(e&&e.unused&&e.unused.length){const n=[...e.unused];n.sort(((t,e)=>t-e)),i+=n.map((n=>Q(e,t[n]))).join("")}return i}function S(){return"*-_".charAt(e(0,2)).repeat(e(3,6))}function O({level:t=[1,6],size:n=[1,8],content:r}){const o=r||p({size:n});return`${"#".repeat(e(...t))} ${o}`}function A({lang:t,content:n,size:r,fenceChar:o="`"}){return"random"===o&&(o="`~".charAt(e(0,1))),n=n||K({lang:t,size:r}),`${o.repeat(3)}${t||""}\n${n}\n${o.repeat(3)}`}function C({sources:t,citation:e,size:n=[20,50]}){const r=["description",E()];return t&&e&&r.push(R(t,e)),p({size:n,decorates:r})}function D({columns:t=[2,4],rows:n=[2,8]}){t=e(...t),n=e(...n);const r=[...N({size:1},t-1),{size:[3,8]}],o=[p({size:t,output:"array"}),r.map((()=>"---"))];for(let t=0;n-1>t;t++)o.push(r.map((({size:t})=>p({size:t}))));return o.map(G).join("\n")}function I({url:t,imageSize:e=[400,250],...n}={}){return t=t||s(e),``}const F=["ordered","bullet","task"];function T({features:t,type:n="random",count:r=[1,8],size:o=[5,15]}){r="number"==typeof r?r:e(...r);const s="random"===n?F[Math.floor(3*Math.random())]:n,i=[];for(;r>0;){const a=e(1,r);let u=C({features:t,size:o});a>1&&(u+="\n"+T({features:t,type:n,count:a-1,size:o})),i.push(J(s,u)),r-=a}return i.join("\n")}const L={"code-span":()=>["`","`"],"emphasis-1":()=>N(H(1),2),"emphasis-2":()=>N(H(2),2),"emphasis-3":()=>N(H(3),2),strikethrough:()=>["~","~"],link:({url:t="https://miso.ai"}={})=>["[",`](${t})`]};function H(t=[1,3]){return t="number"==typeof t?t:e(...t),"_*".charAt(e(0,1)).repeat(t)}const P=Object.keys(L),U=new Set(P);function E({features:t=P,size:n=[1,3],rest:r=[0,8]}={}){t=t.filter((t=>U.has(t)));const s=o([...t]);let i=s.length-1;const a=()=>"number"==typeof r?r:e(...r);return function*(r){let o,u=a();yield*l(r,(function*(r,c){if(!o&&0===u){const[a,c]=L[0>i?t[e(0,t.length-1)]:s[i--]]();r=`${a}${r}`,u="number"==typeof n?n:e(...n),o=c}if(u--,o){const t=r.length,e=r.charAt(t-1);"."===(l=e)||","===l||"!"===l||"?"===l||":"===l||";"===l?(r=`${r.substring(0,t-1)}${o}${e}`,o=void 0,u=a()):(c||0===u)&&(r=`${r}${o}`,o=void 0,u=a())}var l;yield r}))}}function R(t,{density:n=.667,unused:r,...o}){const s=t.length;return function*(i){for(const a of i)"."===a.charAt(a.length-1)&&Math.random()<n?yield`${a}${Q(o,t[r&&r.length?r.pop():e(0,s-1)])}`:yield a}}function W({size:t=[1,3],content:e}={}){return e||p({size:t})}function B(t,e){return e.split("\n").map((e=>" ".repeat(t)+e)).join("\n")}function J(t,e){const[n,r]=e.split("\n",2),o=`${function(t,e="random"){switch(t){case"ordered":return"1.";case"bullet":return"-";case"task":return`- [${("random"===e?.5>Math.random():e)?"x":" "}]`;default:throw Error("unknown list item type: "+t)}}(t)} ${n}`;return r?o+"\n"+B("ordered"===t?3:2,r):o}function K({lang:t,size:e=[10,30]}){return t&&j[t]?j[t]():p({output:"multiline",size:e})}function G(t){return`| ${t.join(" | ")} |`}function N(t,e){const n=[];for(let r=0;e>r;r++)n.push("function"==typeof t?t():t);return n}function Q({link:t,start:e,end:n},{index:r,url:o}){return t?`[${e}${r}${n}](${o})`:`${e}${r}${n}`}var V=Object.freeze({__proto__:null,atxHeading:O,blockquote:function({size:t=[3,5]}){return p({size:t}).split("\n").map((t=>"> "+t)).join("\n")},codeSpan:function(t){return`\`${W(t)}\``},decorateCitation:R,decorateInlineFeatures:E,emphasis:function({level:t=[1,3],options:n}){t="number"==typeof t?t:e(...t);const r="_*".charAt(e(0,1)).repeat(t);return`${r}${W(n)}${r}`},fencedCodeBlock:A,hr:S,image:I,indent:B,indentedCodeBlock:function({lang:t,content:e,size:n}){return B(4,e=e||K({lang:t,size:n}))},link:function({url:t="https://miso.ai",...e}={}){return`[${W(e)}](${t})`},linkReferenceDefinition:function({label:t,destination:e,title:n}){return`[${t}]: ${e}${void 0!==n?" "+n:""}`},list:T,listItem:J,markdown:k,paragraph:C,setextHeading:function({level:t=[1,2],size:n=[1,8],content:r}){return`${r||p({size:n})}\n${"=-".charAt(e(...t)-1).repeat(3)}`},table:D});const Z=864e5,X=7*Z;function Y({}={}){const t=Date.now()-Z,e=t-8*X;return new Date(e+Math.random()*(t-e)).toISOString()}function tt({size:t=300}={}){return s(t)}function et({size:t=[1,3]}={}){return p({size:t,decorates:["title"],output:"array"})}function nt({size:t=[1,4]}={}){return p({size:t,output:"array"})}function rt({size:t=[2,6]}={}){return p({size:t,decorates:["title"]})}function ot({size:t=[10,20],...e}={}){return p({size:t,decorates:[Object.keys(e).length?["description",e]:"description"]})}function st({paragraphs:t=8,sections:e,paragraph:n,image:r}={}){n={size:[30,60],...n},r={size:[480,270],...r},void 0===e&&(e=Math.floor(t*(1+Math.random())/4));const o=[],s=t/(e=Math.max(1,Math.min(e,t)));let i=0;for(let t=0;e>t;t++){for(t>0&&o.push(`<h4>${rt()}</h4>`);i++<(t+1)*s;)o.push(`<p>${ot(n)}</p>`);o.push(`<div class="image-container"><img src="${tt(r)}"></div>`)}return o.join("")}function it(){return Math.random()>.3?"IN_STOCK":"OUT_OF_STOCK"}function at(){return Math.floor(1e4*Math.random())/100}function ut(){return Math.floor(500*Math.random())/100+1}function ct({sources:t,format:e,citation:n,sampling:r,features:o}){if("markdown"===e){let e=1;return k({sources:t=t.map((({url:t})=>({url:t,index:e++}))),citation:n,sampling:r,features:o})}return p({min:a(50,r),max:a(50,r),decorates:["description"]})}var lt=Object.freeze({__proto__:null,answer:ct,authors:et,availability:it,date:Y,description:ot,html:st,image:tt,price:at,rating:ut,tags:nt,title:rt});function*dt({rows:t,...e}={}){for(let n=0;t>n;n++)yield ft({...e,index:n})}function ft({}={}){const t=r(),e=n(at,[1,2]);return e.sort(),{product_id:t,authors:et(),categories:[],tags:nt(),title:rt(),description:ot(),cover_image:tt(),url:"https://dummy.miso.ai/products/"+t,sale_price:e[0],original_price:e[e.length-1],rating:ut(),availability:it()}}const pt=new Set(["cover_image","url","created_at","updated_at","published_at"]);function*mt({rows:t,...e}={}){for(let n=0;t>n;n++)yield ht({...e,index:n})}function ht({html:t,fl:e=[]}={}){const n={product_id:r(),authors:et(),categories:[],tags:nt(),title:rt({size:[4,10]}),snippet:ot({size:[20,40]}),html:st(t)};for(const t of e)pt.has(t)&&(n[t]=gt(n,t));return n}function gt({product_id:t},e){switch(e){case"cover_image":return tt();case"url":return"/products/"+t;case"created_at":case"updated_at":case"published_at":return Y()}}function*_t({rows:t=5,...e}={}){for(let n=0;t>n;n++)yield wt({...e,index:n})}function wt({}={}){return ot({size:[4,8],punctuation:"?"})}function bt({question:e,parent_question_id:n,source_fl:r=["cover_image","url"],related_resource_fl:s=["cover_image","url"],cite_link:a=!1,cite_start:u="[",cite_end:c="]",timestamp:l=Date.now()},{answerFormat:d="markdown",answerSampling:f,answerLanguages:p=[]}={}){const m=t(),h=i(l),g=void 0!==f?Math.max(0,Math.min(1,f)):void 0,_=p.length?p.map((t=>"lang-"+t)):void 0,w=[...mt({rows:yt(6,8,g),fl:s})].map(vt),b=[...mt({rows:yt(4,6,g),fl:r})].map(vt);return{question:e,question_id:m,...n&&{parent_question_id:n},datetime:h,answer:ct({sources:b,citation:{link:"0"!==a&&!!a,start:u,end:c,unused:o([...Array(b.length).keys()])},format:d,sampling:g,features:_}),sources:b,related_resources:w,followup_questions:[..._t({rows:yt(3,6)})]}}function yt(t,n,r){return e(a(t,r),a(n,r))}function vt({html:t,...e}){return e}var $t=Object.freeze({__proto__:null,answer:bt,articles:mt,fields:lt,lorem:M,md:V,products:dt,questions:_t,utils:d});const zt=[{name:"fetch",duration:1.5,text:"Checking the question and fetching results... "},{name:"verify",duration:1.5,text:"Verifying results... "},{name:"generate",duration:1.5,text:"Generating answer... "}];class qt{constructor(t={}){this._options=t,this._answers=new Map}questions(t,e={}){const n=new Mt(t,{...this._options,...e}),{question_id:r}=n;return this._answers.set(r,n),{question_id:r}}answer(t){const e=this._answers.get(t);if(!e){const e=Error("Question not found: "+t);throw e.status=404,e}return e.get()}related_questions(t){return{related_questions:[..._t(t)]}}}class Mt{constructor(t,{answerFormat:e,answerSampling:n,answerLanguages:r,...o}={}){this._options=Object.freeze(o);const s=this.timestamp=Date.now();this._data=bt({...t,timestamp:s},{answerFormat:e,answerSampling:n,answerLanguages:r})}get question_id(){return this._data.question_id}get(){const t=(Date.now()-this.timestamp)*(this._options.speedRate||1)/1e3,[e,n,r]=this._answer(t),o=this._sources(t,r),s=this._related_resources(t,r),i=this._followup_questions(t,r),{question_id:a,question:u,datetime:c,parent_question_id:l}=this._data;return{answer:n,answer_stage:e,datetime:c,finished:r,parent_question_id:l,question:u,question_id:a,sources:o,related_resources:s,followup_questions:i}}_answer(t){for(const e of zt)if(0>(t-=e.duration))return[e.name,e.text,!1];const{answer:e}=this._data,n=Math.floor(100*t),r=n>=e.length;return["result",r?e:e.slice(0,n),r]}_sources(t,e){const{sources:n}=this._data;if(e)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}_related_resources(t,e){const{related_resources:n}=this._data;if(e)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}_followup_questions(t,e){const{followup_questions:n}=this._data;if(e||!n)return n;const{length:r}=n;return n.slice(0,Math.floor(r*t/3))}}class xt{constructor(t){this._options=t}search({rows:t=5}){return{products:[...dt({rows:t})]}}}class jt{constructor(t){this._options=t}user_to_products({rows:t=5}){return{products:[...dt({rows:t})]}}product_to_products({rows:t=5}){return{products:[...dt({rows:t})]}}}class kt{constructor(t){this._options=t}upload(t){return[]}}class St{constructor(t){this._options=t}upload(t){return[]}ids(){const t=[];for(let e=0;5e3>e;e++)t.push(Ot(e));return{ids:t}}}function Ot(t){return`${10>t?"p_000":100>t?"p_00":1e3>t?"p_0":"p_"}${t}`}class At{constructor(t){this.ask=new qt(t),this.search=new xt(t),this.recommendation=new jt(t),this.interactions=new kt(t),this.products=new St(t)}}return{buildApi:(...t)=>new At(...t),data:$t}}));
|
package/package.json
CHANGED
package/src/data/answers.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomInt, formatDatetime, sample, uuid } from './utils.js';
|
|
1
|
+
import { randomInt, formatDatetime, sample, uuid, shuffle } from './utils.js';
|
|
2
2
|
import * as fields from './fields.js';
|
|
3
3
|
import { articles } from './articles.js';
|
|
4
4
|
import { questions } from './questions.js';
|
|
@@ -8,6 +8,9 @@ export function answer({
|
|
|
8
8
|
parent_question_id,
|
|
9
9
|
source_fl = ['cover_image', 'url'],
|
|
10
10
|
related_resource_fl = ['cover_image', 'url'],
|
|
11
|
+
cite_link = false,
|
|
12
|
+
cite_start = '[',
|
|
13
|
+
cite_end = ']',
|
|
11
14
|
timestamp = Date.now(),
|
|
12
15
|
}, { answerFormat = 'markdown', answerSampling, answerLanguages = [] } = {}) {
|
|
13
16
|
|
|
@@ -17,9 +20,16 @@ export function answer({
|
|
|
17
20
|
const sampling = answerSampling !== undefined ? Math.max(0, Math.min(1, answerSampling)) : undefined;
|
|
18
21
|
const features = answerLanguages.length ? answerLanguages.map(language => `lang-${language}`) : undefined;
|
|
19
22
|
|
|
20
|
-
const answer = fields.answer({ format: answerFormat, sampling, features });
|
|
21
23
|
const related_resources = [...articles({ rows: sampleRandomInt(6, 8, sampling), fl: related_resource_fl })].map(excludeHtml);
|
|
22
24
|
const sources = [...articles({ rows: sampleRandomInt(4, 6, sampling), fl: source_fl })].map(excludeHtml);
|
|
25
|
+
|
|
26
|
+
const citation = {
|
|
27
|
+
link: cite_link !== '0' && !!cite_link,
|
|
28
|
+
start: cite_start,
|
|
29
|
+
end: cite_end,
|
|
30
|
+
unused: shuffle([...Array(sources.length).keys()]),
|
|
31
|
+
};
|
|
32
|
+
const answer = fields.answer({ sources, citation, format: answerFormat, sampling, features });
|
|
23
33
|
const followup_questions = [...questions({ rows: sampleRandomInt(3, 6) })];
|
|
24
34
|
|
|
25
35
|
return {
|
package/src/data/fields.js
CHANGED
|
@@ -88,10 +88,12 @@ export function rating() {
|
|
|
88
88
|
return Math.floor(Math.random() * 500) / 100 + 1;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
export function answer({ format, sampling, features }) {
|
|
91
|
+
export function answer({ sources, format, citation, sampling, features }) {
|
|
92
92
|
switch (format) {
|
|
93
93
|
case 'markdown':
|
|
94
|
-
|
|
94
|
+
let index = 1;
|
|
95
|
+
sources = sources.map(({ url }) => ({ url, index: index++ }));
|
|
96
|
+
return md.markdown({ sources, citation, sampling, features });
|
|
95
97
|
case 'plaintext':
|
|
96
98
|
default:
|
|
97
99
|
return lorem.lorem({
|
package/src/data/lorem.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomInt, gaussRandom } from './utils.js';
|
|
1
|
+
import { randomInt, gaussRandom, iterateWithLastItemSignal as iterateWithLastItemSignal } from './utils.js';
|
|
2
2
|
import DEFAULT_WORDS from './words.js';
|
|
3
3
|
|
|
4
4
|
export function lorem({ decorates = [], output = 'string', size, min, max, ...options } = {}) {
|
|
@@ -105,27 +105,18 @@ export function description({
|
|
|
105
105
|
punctuation = '.',
|
|
106
106
|
} = {}) {
|
|
107
107
|
return function *(iterator) {
|
|
108
|
-
let word;
|
|
109
108
|
let slen = 0;
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
yield word;
|
|
113
|
-
}
|
|
114
|
-
word = _word;
|
|
109
|
+
|
|
110
|
+
yield* iterateWithLastItemSignal(iterator, function *(word, last) {
|
|
115
111
|
if (slen === 0) {
|
|
116
112
|
word = capitalize(word);
|
|
117
113
|
slen = gaussMS(wordsPerSentence);
|
|
118
114
|
}
|
|
119
|
-
if (--slen === 0) {
|
|
120
|
-
word += punctuation;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
if (word) {
|
|
124
|
-
if (!word.endsWith(punctuation)) {
|
|
115
|
+
if (--slen === 0 || last) {
|
|
125
116
|
word += punctuation;
|
|
126
117
|
}
|
|
127
118
|
yield word;
|
|
128
|
-
}
|
|
119
|
+
});
|
|
129
120
|
};
|
|
130
121
|
}
|
|
131
122
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomInt, imageUrl, shuffle } from '../utils.js';
|
|
1
|
+
import { randomInt, imageUrl, shuffle, iterateWithLastItemSignal } from '../utils.js';
|
|
2
2
|
import * as lorem from '../lorem.js';
|
|
3
3
|
import * as languages from './languages.js';
|
|
4
4
|
|
|
@@ -21,25 +21,32 @@ function extractLangFeatures(features = []) {
|
|
|
21
21
|
return [[...languages], rest];
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
export function markdown({ features, blocks = [8, 12], sampling = 1 } = {}) {
|
|
24
|
+
export function markdown({ sources, citation, features, blocks = [8, 12], sampling = 1 } = {}) {
|
|
25
25
|
let languages = [];
|
|
26
26
|
[languages, features] = extractLangFeatures(features);
|
|
27
27
|
// TODO: block features
|
|
28
|
-
|
|
28
|
+
let result = sample([
|
|
29
29
|
() => atxHeading({ features }),
|
|
30
|
-
() => paragraph({ features }),
|
|
30
|
+
() => paragraph({ sources, citation, features }),
|
|
31
31
|
...languages.map(lang => () => fencedCodeBlock({ lang, features })),
|
|
32
32
|
...(languages.length ? [] : [() => fencedCodeBlock({ features })]),
|
|
33
|
-
() => paragraph({ features }),
|
|
33
|
+
() => paragraph({ sources, citation, features }),
|
|
34
34
|
() => table({ features }),
|
|
35
35
|
() => image(),
|
|
36
|
-
() => paragraph({ features }),
|
|
36
|
+
() => paragraph({ sources, citation, features }),
|
|
37
37
|
() => hr(),
|
|
38
38
|
() => atxHeading({ features }),
|
|
39
|
-
() => paragraph({ features }),
|
|
39
|
+
() => paragraph({ sources, citation, features }),
|
|
40
40
|
() => list({ features }),
|
|
41
|
-
() => paragraph({ features }),
|
|
41
|
+
() => paragraph({ sources, citation, features }),
|
|
42
42
|
], sampling).join('\n\n');
|
|
43
|
+
if (citation && citation.unused && citation.unused.length) {
|
|
44
|
+
// flush all unused citations
|
|
45
|
+
const indicies = [...citation.unused];
|
|
46
|
+
indicies.sort((a, b) => a - b);
|
|
47
|
+
result += indicies.map(index => _citation(citation, sources[index])).join('');
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
43
50
|
}
|
|
44
51
|
|
|
45
52
|
function sample(fns, sampling) {
|
|
@@ -87,9 +94,13 @@ export function fencedCodeBlock({ lang, content, size, fenceChar = '`' }) {
|
|
|
87
94
|
return `${fenceChar.repeat(3)}${lang || ''}\n${content}\n${fenceChar.repeat(3)}`;
|
|
88
95
|
}
|
|
89
96
|
|
|
90
|
-
export function paragraph({ features, size = [20, 50] }) {
|
|
97
|
+
export function paragraph({ sources, citation, features, size = [20, 50] }) {
|
|
91
98
|
// force all inline features
|
|
92
|
-
|
|
99
|
+
const decorates = ['description', decorateInlineFeatures()];
|
|
100
|
+
if (sources && citation) {
|
|
101
|
+
decorates.push(decorateCitation(sources, citation));
|
|
102
|
+
}
|
|
103
|
+
return lorem.lorem({ size, decorates });
|
|
93
104
|
}
|
|
94
105
|
|
|
95
106
|
export function table({ features, columns = [2, 4], rows = [2, 8] }) {
|
|
@@ -171,7 +182,7 @@ const INLINE_FEATURE_LIST = Object.keys(INLINE_FEATURES);
|
|
|
171
182
|
const INLINE_FEATURE_SET = new Set(INLINE_FEATURE_LIST);
|
|
172
183
|
|
|
173
184
|
// decorator //
|
|
174
|
-
export function
|
|
185
|
+
export function decorateInlineFeatures({ features = INLINE_FEATURE_LIST, size = [1, 3], rest = [0, 8] } = {}) {
|
|
175
186
|
features = features.filter(f => INLINE_FEATURE_SET.has(f));
|
|
176
187
|
|
|
177
188
|
const unused = shuffle([...features]);
|
|
@@ -184,30 +195,53 @@ export function decorate({ features = INLINE_FEATURE_LIST, size = [1, 3], rest =
|
|
|
184
195
|
return function *(iterator) {
|
|
185
196
|
let count = rollRest();
|
|
186
197
|
let suffix;
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if
|
|
190
|
-
|
|
198
|
+
|
|
199
|
+
yield *iterateWithLastItemSignal(iterator, function *(word, last) {
|
|
200
|
+
// prefix if necessary
|
|
201
|
+
if (!suffix && count === 0) {
|
|
202
|
+
const [prefix, s] = INLINE_FEATURES[rollFeatureType()]();
|
|
203
|
+
word = `${prefix}${word}`;
|
|
204
|
+
count = rollFeatureSize();
|
|
205
|
+
suffix = s;
|
|
191
206
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
207
|
+
|
|
208
|
+
// consume word count
|
|
209
|
+
count--;
|
|
210
|
+
|
|
211
|
+
// suffix if necessary
|
|
212
|
+
if (suffix) {
|
|
213
|
+
const len = word.length;
|
|
214
|
+
const lastChar = word.charAt(len - 1);
|
|
215
|
+
if (isPunctuation(lastChar)) {
|
|
216
|
+
word = `${word.substring(0, len - 1)}${suffix}${lastChar}`;
|
|
217
|
+
suffix = undefined;
|
|
218
|
+
count = rollRest();
|
|
219
|
+
} else if (last || count === 0) {
|
|
220
|
+
word = `${word}${suffix}`;
|
|
195
221
|
suffix = undefined;
|
|
196
222
|
count = rollRest();
|
|
197
|
-
} else {
|
|
198
|
-
const [prefix, s] = INLINE_FEATURES[rollFeatureType()]();
|
|
199
|
-
lastWord = `${prefix}${word}`;
|
|
200
|
-
suffix = s;
|
|
201
|
-
count = rollFeatureSize();
|
|
202
223
|
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// output
|
|
227
|
+
yield word;
|
|
228
|
+
});
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function decorateCitation(sources, { density = 0.667, unused, ...options }) {
|
|
233
|
+
const sourceLength = sources.length;
|
|
234
|
+
const rollIndex = () => unused && unused.length ? unused.pop() : randomInt(0, sourceLength - 1);
|
|
235
|
+
|
|
236
|
+
return function *(iterator) {
|
|
237
|
+
for (const word of iterator) {
|
|
238
|
+
// not ended with alphabet or number -> last word in sentence
|
|
239
|
+
if (word.charAt(word.length - 1) === '.' && Math.random() < density) {
|
|
240
|
+
yield `${word}${_citation(options, sources[rollIndex()])}`;
|
|
203
241
|
} else {
|
|
204
|
-
|
|
205
|
-
count--;
|
|
242
|
+
yield word;
|
|
206
243
|
}
|
|
207
244
|
}
|
|
208
|
-
if (lastWord) {
|
|
209
|
-
yield suffix !== undefined ? `${lastWord}${suffix}` : lastWord;
|
|
210
|
-
}
|
|
211
245
|
};
|
|
212
246
|
}
|
|
213
247
|
|
|
@@ -260,3 +294,11 @@ function multiply(obj, i) {
|
|
|
260
294
|
}
|
|
261
295
|
return arr;
|
|
262
296
|
}
|
|
297
|
+
|
|
298
|
+
function isPunctuation(char) {
|
|
299
|
+
return char === '.' || char === ',' || char === '!' || char === '?' || char === ':' || char === ';';
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function _citation({ link, start, end }, { index, url }) {
|
|
303
|
+
return link ? `[${start}${index}${end}](${url})` : `${start}${index}${end}`;
|
|
304
|
+
}
|
package/src/data/utils.js
CHANGED
|
@@ -3,7 +3,7 @@ export function uuid() {
|
|
|
3
3
|
}
|
|
4
4
|
|
|
5
5
|
export function randomInt(min, max) {
|
|
6
|
-
return max == null || (max <= min) ? min : (min + Math.floor(Math.random() * (max - min)));
|
|
6
|
+
return max == null || (max <= min) ? min : (min + Math.floor(Math.random() * (max - min + 1)));
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
// TODO: pass in size
|
|
@@ -50,3 +50,16 @@ export function gaussRandom() {
|
|
|
50
50
|
function uniformRandom() {
|
|
51
51
|
return Math.random() * 2 - 1;
|
|
52
52
|
}
|
|
53
|
+
|
|
54
|
+
export function *iterateWithLastItemSignal(iterator, fn) {
|
|
55
|
+
let last;
|
|
56
|
+
for (const item of iterator) {
|
|
57
|
+
if (last) {
|
|
58
|
+
yield* fn(last);
|
|
59
|
+
}
|
|
60
|
+
last = item;
|
|
61
|
+
}
|
|
62
|
+
if (last) {
|
|
63
|
+
yield* fn(last, true);
|
|
64
|
+
}
|
|
65
|
+
}
|